# -*- coding: utf-8 -*-

"""
pass
"""

from framework.admincontroller import AdminController
import json
import hashlib
from models.admin import AdminModel
from framework.session import Session
import tornado.web

class AdminCtrl(AdminController):
    """admin controller"""
    # __model = None

    # Entry points
    # def initialize(self):
    #    self.__model = AdminModel()

    # def prepare(self):
    #    pass
    #    self.write("begin")

    @tornado.web.authenticated
    def post(self):
        """admin password modify handler"""
        err = dict(err=1, href='/')
        if not self.current_user.get("_id"):
            err['msg'] = u"无法获取用户信息，请稍候再试"
            self.ajax_out(**err)
            return
        if self.get_argument("newpass").strip() != self.get_argument("newpass2").strip():
            err['msg'] = u"新密码两次不一致"
            self.ajax_out(**err)
            return
        # m = AdminModel()
        # user = m.find_one({'_id': self.current_user.get('_id')})
        # if not user:
        #    err['msg'] = u"无法获取用户信息，请稍候再试"
        #    self.ajax_out(**err)
        #    return
        password = self.get_argument("user_pass").strip()
        m = hashlib.md5(password)
        password = m.hexdigest()
        if self.current_user.get("pass") != password:
            err['msg'] = u"用户密码不符"
            self.ajax_out(**err)
            return
        pw = hashlib.md5(self.get_argument("newpass").strip())
        password = pw.hexdigest()
        self.current_user['pass'] = password
        admin = AdminModel()
        admin.update({'_id': self.current_user['_id']}, self.current_user)
        err['err'] = 0
        self.current_user = None
        thor = self.get_secure_cookie("thor")
        sess = Session(thor)
        sess.clear_all()
        # clear cookies
        self.clear_cookie("thor")
        self.clear_cookie("tracknick")
        self.clear_cookie("token")
        self.ajax_out(**err)
        return